package com.woniuxy.yuekeuser.common;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;


import com.woniuxy.yuekeuser.config.AlipayConfig;

import com.woniuxy.yuekeuser.model.TOrder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliUtil {
    //付款调用此方法，传入order对象，对象内应包含金额，订单号，车辆驶入驶出时间(非必须)
    public static Result pay(TOrder order){
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
       log.info("传到支付宝的订单详细{}",order);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderId()+"";
        //付款金额，必填   如果你的类型是double需写成  price+"" 的形式，否则当含有小数部分时金额错误
        String total_amount = order.getOrderPrice()+"";
        //订单名称，必填
        String subject =order.getOrderType()+"";
        //商品描述，可空
        String body = "订单产生时间：" +order.getDownorderTime();

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1h";

        String qr_code_timeout_express = "2m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"qr_code_timeout_express\":\""+ qr_code_timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            return Result.success(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.fail("前往付款页面失败");
        }
    }

}
